/**
 * Project Name:pango
 * File Name:UserServiceImpl.java
 * Package Name:com.pango.system.services.impl
 * Date:2014-5-27下午11:02:39
 * Copyright (c) 2014, fuqiongsong@gmail.com All Rights Reserved.
 *
*/

package com.pango.system.services.impl;

import java.util.HashSet;
import java.util.List;
import java.util.Set;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import com.pango.core.paginator.domain.PageBounds;
import com.pango.core.security.shiro.utils.PasswordHelper;
import com.pango.system.mapper.RoleMapper;
import com.pango.system.mapper.UserMapper;
import com.pango.system.model.Role;
import com.pango.system.model.User;
import com.pango.system.services.UserService;
/**
 * ClassName:UserServiceImpl <br/>
 * Date:     2014-5-27 下午11:02:39 <br/>
 * @author   thierry.fu
 * @version  
 * @since    JDK 1.6
 * @see 	 
 */
@Service
public class UserServiceImpl implements UserService{

	@Autowired
	private UserMapper userMapper;
	
	@Autowired
	private RoleMapper roleMapper;
	
	@Override
	public User createUser(User user) {
		PasswordHelper passwordHelper = new PasswordHelper();
		passwordHelper.encryptPassword(user);
		long id = userMapper.insert(user);
		return userMapper.selectByPrimaryKey(id);
	}

	@Override
	public User updateUser(User user) {
		long id = userMapper.updateByPrimaryKey(user);
		return userMapper.selectByPrimaryKey(id);
	}

	@Override
	public void deleteUser(Long userId) {
		// TODO Auto-generated method stub
		userMapper.deleteByPrimaryKey(userId);
	}

	@Override
	public void changePassword(Long userId, String newPassword) {
		// TODO Auto-generated method stub
		User user = userMapper.selectByPrimaryKey(userId);
		PasswordHelper passwordHelper = new PasswordHelper();
		passwordHelper.encryptPassword(user);
		userMapper.updateByPrimaryKey(user);
	}


	@Override
	public User findByUsername(String username) {
		return userMapper.selectByUsername(username);
	}

	@Override
	public Set<String> findRoles(String username) {
		List<Role> roles = roleMapper.selectRolesByUsername(username);
		Set<String> roleNames = new HashSet<String>();
		for (Role role : roles) {
			roleNames.add(role.getRole());
		}
		return roleNames;
	}

	@Override
	public Set<String> findPermissions(String username) {
		// TODO Auto-generated method stub
		return null;
	}
	
	@Override
	public List<User> getAll(PageBounds pageBounds) {
		return userMapper.selectAll(pageBounds);
	}
	
	@Override
	public User findById(Long id) {
		 return userMapper.selectByPrimaryKey(id);
	}

}
